import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Random;

@Aspect
@Component
public class OrderServiceAspect {

    // 1. 前置增强：在add, delete, find方法前输出
    @Before("execution(* com.example.demo.service.OrderService.add(..)) || " +
            "execution(* com.example.demo.service.OrderService.delete(..)) || " +
            "execution(* com.example.demo.service.OrderService.find(..))")
    public void beforeAdvice(JoinPoint joinPoint) {
        System.out.println("hello, 我是一个前置增强");
    }

    // 2. 后置增强：在add, delete方法后输出
    @After("execution(* com.example.demo.service.OrderService.add(..)) || " +
            "execution(* com.example.demo.service.OrderService.delete(..))")
    public void afterAdvice(JoinPoint joinPoint) {
        System.out.println("bye, 我是一个后置增强");
    }

    // 3. 获取方法返回值并输出
    @AfterReturning(pointcut = "execution(* com.example.demo.service.OrderService.add(..)) || " +
            "execution(* com.example.demo.service.OrderService.delete(..)) || " +
            "execution(* com.example.demo.service.OrderService.find(..))",
            returning = "result")
    public void afterReturningAdvice(JoinPoint joinPoint, Object result) {
        System.out.println("方法 " + joinPoint.getSignature().getName() + " 的返回值是: " + result);
    }

    // 4. 输出方法执行时间
    @Around("execution(* com.example.demo.service.OrderService.add(..)) || " +
            "execution(* com.example.demo.service.OrderService.delete(..)) || " +
            "execution(* com.example.demo.service.OrderService.find(..))")
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

        Object result = proceedingJoinPoint.proceed();

        long endTime = System.currentTimeMillis();
        System.out.println("方法 " + proceedingJoinPoint.getSignature().getName() + " 执行时间: " + (endTime - startTime) + "毫秒");

        return result;
    }

    // 5. 权限检查
    @Before("execution(* com.example.demo.service.OrderService.add(..)) || " +
            "execution(* com.example.demo.service.OrderService.delete(..))")
    public void checkPermission(JoinPoint joinPoint) throws Exception {
        Random random = new Random();
        int permission = random.nextInt(2); // 生成0或1

        if (permission == 0) {
            System.out.println("权限检查通过，有权限执行 " + joinPoint.getSignature().getName() + " 方法");
        } else {
            System.out.println("权限检查失败，没有权限执行 " + joinPoint.getSignature().getName() + " 方法");
            throw new Exception("没有权限执行此操作");
        }
    }
}
